package com.yinsin.utils;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.yinsin.other.LogHelper;

public class IniUtils {

    private static LogHelper logger = LogHelper.getLogger(IniUtils.class);

    public static HashMap<String, HashMap<String, HashMap<String, String>>> sections = new HashMap<String, HashMap<String, HashMap<String, String>>>();
    private String currentSecion, currTag;
    private HashMap<String, HashMap<String, String>> current;
    private HashMap<String, String> cfgMap;
    private static String file = "/cfg.ini";
    private static boolean isinited = false;
    static String baseDir = "/";

    private IniUtils() {
    }

    private static class IniUtilsHolder {
        private static final IniUtils INSTANCE = new IniUtils();
    }

    public static final IniUtils getInstance() {
        return IniUtilsHolder.INSTANCE;
    }

    /**
     * 初始化配置
     * 
     * @param fileName
     */
    public void init(String fileName) {
        try {
            synchronized (IniUtils.class) {
                if (!isinited) {
                    if (SystemUtils.isWindow()) {
                        if (fileName.indexOf(":") != -1) {
                            file = fileName;
                        } else {
                            baseDir = ObjectUtils.getBaseDir(fileName);
                            FileUtils.createDir(baseDir);
                            file = baseDir + fileName;
                        }
                    } else if (SystemUtils.isLinux()) {
                        file = fileName;
                    }
                    // FileUtils.createFile(file);
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    read(reader);
                    reader.close();
                }
            }
        } catch (Exception e) {
            logger.error("初始化配置失败", e);
        }
    }

    private void read(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            parseLine(line);
        }
    }

    private void parseLine(String line) {
        line = line.trim();
        if(!line.startsWith("#")){
        	if (line.matches("\\[.*\\]")) {
        		currentSecion = line.replaceFirst("\\[(.*)\\]", "$1");
        		current = new HashMap<String, HashMap<String, String>>();
        		sections.put(currentSecion, current);
        		cfgMap = new HashMap<String, String>();
        	} else if (line.matches("<.*>")) {
        		currTag = line.replaceFirst("<(.*)>", "$1");
        		cfgMap = new HashMap<String, String>();
        		current.put(currTag, cfgMap);
        	} else if (line.matches(".*=.*")) {
        		if (cfgMap != null) {
        			int i = line.indexOf('=');
        			String name = line.substring(0, i);
        			String value = line.substring(i + 1);
        			cfgMap.put(name, value);
        		}
        	}
        }
    }

    /**
     * 获取配置集合
     * 
     * @param section
     * @return
     */
    public HashMap<String, HashMap<String, String>> getConfig(String section) {
        HashMap<String, HashMap<String, String>> p = sections.get(section);
        if (p == null) {
            return null;
        }
        return p;
    }

    /**
     * 获取指定索引的配置集合
     * 
     * @param section
     * @param tag
     * @return
     */
    public HashMap<String, String> getConfig(String section, String tag) {
        HashMap<String, HashMap<String, String>> p = sections.get(section);
        if (p == null) {
            return null;
        }
        HashMap<String, String> valMap = p.get(tag);
        if (valMap == null) {
            return null;
        }
        return valMap;
    }

    /**
     * 获取配置值
     * 
     * @param section
     * @param tag
     * @param name
     * @return
     */
    public String getValue(String section, String tag, String name) {
        HashMap<String, String> valMap = getConfig(section, tag);
        if (valMap == null) {
            return null;
        }
        return valMap.get(name);
    }

    public IniUtils putValue(String section, String tag, String name, String value) {
        HashMap<String, HashMap<String, String>> map = sections.get(section);
        HashMap<String, String> cfg = null;
        if (map == null) {
            map = new HashMap<String, HashMap<String, String>>();
            sections.put(section, map);
            cfg = new HashMap<String, String>();
            map.put(tag, cfg);
        } else {
            cfg = map.get(tag);
            if (cfg == null) {
                cfg = new HashMap<String, String>();
                map.put(tag, cfg);
            }
        }
        cfg.put(name, value);
        return this;
    }

    /**
     * 获取正激活使用的配置
     * 
     * @param section
     * @return
     */
    public HashMap<String, String> getActiveCfg(String section) {
        HashMap<String, HashMap<String, String>> map = sections.get(section);
        HashMap<String, String> result = null, temp = null;
        if (map != null) {
            String isSelected = "";
            for (Map.Entry<String, HashMap<String, String>> ent : map.entrySet()) {
                temp = ent.getValue();
                isSelected = temp.get("isSelected");
                if (isSelected != null && isSelected.equals("true")) {
                    result = temp;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 替换激活配置
     * 
     * @param section
     * @return
     */
    public HashMap<String, String> replaceActiveCfg(String section, String tag) {
        HashMap<String, HashMap<String, String>> map = sections.get(section);
        HashMap<String, String> result = null;
        if (map != null) {
            result = map.get(tag);
            String key = "";
            for (Map.Entry<String, HashMap<String, String>> ent : map.entrySet()) {
                key = ent.getKey();
                if (key.equals(tag)) {
                    this.putValue(section, key, "isSelected", "true");
                } else {
                    this.putValue(section, key, "isSelected", "false");
                }
            }
        }
        return result;
    }

    public IniUtils save() {
        try {
            StringBuffer sb = new StringBuffer();
            HashMap<String, HashMap<String, String>> currMap = null;
            HashMap<String, String> cfgMap = null;
            for (Map.Entry<String, HashMap<String, HashMap<String, String>>> entry : sections.entrySet()) {
                sb.append("[").append(entry.getKey()).append("]\r\n");
                currMap = entry.getValue();

                if (currMap != null && currMap.entrySet().size() > 0) {
                    for (Map.Entry<String, HashMap<String, String>> ent : currMap.entrySet()) {
                        sb.append("<").append(ent.getKey()).append(">\r\n");
                        cfgMap = ent.getValue();

                        for (Map.Entry<String, String> e : cfgMap.entrySet()) {
                            sb.append(e.getKey() + "=").append(e.getValue() + "\r\n");
                        }
                    }
                }
                sb.append("\r\n");
            }
            OutputStream fos = new FileOutputStream(file);// 加载读取文件流
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public static void main(String[] args) {
        IniUtils reader = IniUtils.getInstance();
        reader.init("/cfg.ini");
        System.out.println(IniUtils.sections);
    }
}